import os
from configparser import ConfigParser
import pymysql
import traceback
class ConfigReader:
    def __init__(self,file):
        self.config = ConfigParser()        # 实例化配置对象
        config_path = os.path.split(os.path.realpath(__file__))[0] + os.sep + file
        self.config.read(config_path,encoding='utf-8')     # 读取配置文件，设置字符编码 utf-8
    def get_option(self,option):
        for section in self.config.sections():      # 循环所有的节  [URL,DATABASE]
            if self.config.has_option(section,option):      # 判断我要找到的option是否存在于section里
                return self.config.get(section,option)      # 如果存在，则返回对应的option信息

class DB:
    def __init__(self,database):
        self.database = database
        """
        账号
        密码
        ip地址
        """
        config = ConfigReader('dev_database.ini')
        self.host = config.get_option(str(database) + "_host")      # crmeb_host
        self.user = config.get_option(str(database) + '_user')
        self.password = config.get_option(str(database) + "_password")
    def connect(self):
        # 创建数据库对象
        self.db = pymysql.connect(user = self.user,password=self.password,database=self.database,host=self.host,cursorclass =
        pymysql.cursors.DictCursor)
        # 创建游标
        self.cursor = self.db.cursor()
    def close(self):
        self.cursor.close()
        self.db.close()
    def searchOne(self,sql):
        self.connect()
        result = None
        try:
            self.cursor.execute(sql)
            result = self.cursor.fetchone()
            return result
        except:
            self.db.rollback()
            traceback.print_exc()
            return result
        finally:
            self.close()
    def searchAll(self,sql):
        self.connect()
        result = None
        try:
            self.cursor.execute(sql)
            result = self.cursor.fetchall()
            return result
        except:
            self.db.rollback()
            traceback.print_exc()
            return result
        finally:
            self.close()
    def __edit(self,sql):
        self.connect()
        result = None
        try:
            self.cursor.execute(sql)
            self.db.commit()
            result = 1
            return result
        except:
            self.db.rollback()
            traceback.print_exc()
            return result
        finally:
            self.close()
    def insert(self,sql):
        return self.__edit(sql)

    def update(self,sql):
        return self.__edit(sql)

    def delete(self,sql):
        return self.__edit(sql)


if __name__ == '__main__':
    # database = 'crmeb'
    # config = ConfigReader('dev_database.ini')
    # print(config.get_option(database + "_host"))
    # print(config.get_option(database + "_user"))
    # print(config.get_option(database + "_password"))
    # 实例化对象
    d1 = DB('crmeb')
    name = "商娜"
    # 调用查询方法
    print(d1.searchAll(f'select id from eb_user_group where group_name="{name}"')[0]['id'])






